package com.bingo.mpa.service;

import java.util.Calendar;
import java.util.LinkedList;
import java.util.Locale;

import com.bingo.mpa.dao.StoreDao;
import com.bingo.mpa.dao.UserDao;
import com.bingo.mpa.pojo.Store;
import com.bingo.mpa.pojo.User;

public class AgentService extends Thread
{
	private static class SingletonHolder
	{
		private static final AgentService INSTANCE = new AgentService();
	}

	private AgentService()
	{
	}

	public static final AgentService getInstance()
	{
		return SingletonHolder.INSTANCE;
	}

	private boolean running = true;
	private LinkedList<Store> queue = new LinkedList<Store>();

	public synchronized void close()
	{
		running = false;
		this.notify();
	}

	@Override
	public void run()
	{
		Store obj = null;
		while (running)
		{
			synchronized (this)
			{
				if (this.queue.isEmpty())
				{
					try
					{
						this.wait();
						continue;
					}
					catch (InterruptedException e)
					{
					}
				}
				else
				{
					obj = queue.poll();
					try
					{
						if (obj == null)
						{
							continue;
						}
						Store tmp = StoreDao.findByName(obj.getName());
						if (tmp == null)
						{
							long sid = StoreDao.save(obj);
							// 同时分配营业员帐号
							User user = new User();
							user.setAid(obj.getAid());
							user.setSid(sid);
							long account = UserDao.getSeq();
							if(account > 0)
							{
								user.setAccount(String.valueOf(account));
								user.setName(obj.getName());
								user.setMobile(obj.getMobile());
								user.setAddress(obj.getAddress());
								user.setRole((byte) 3);
								user.setStatus((byte) 2);
								user.setReg_time(new java.sql.Timestamp(Calendar.getInstance(Locale.CHINA).getTimeInMillis()));
								UserDao.save(user);
							}
						}
						else
						{
							obj.setSid(tmp.getSid());
							StoreDao.update(obj);
							
							//是否有分配帐号
							User usr = UserDao.findBySid(tmp.getSid());
							if(usr == null)
							{
								User user = new User();
								user.setAid(obj.getAid());
								user.setSid(tmp.getSid());
								long account = UserDao.getSeq();
								if(account > 0)
								{
									user.setAccount(String.valueOf(account));
									user.setName(obj.getName());
									user.setMobile(obj.getMobile());
									user.setAddress(obj.getAddress());
									user.setRole((byte) 3);
									user.setStatus((byte) 2);
									user.setReg_time(new java.sql.Timestamp(Calendar.getInstance(Locale.CHINA).getTimeInMillis()));
									UserDao.save(user);
								}
							}
						}
						Thread.sleep(100);
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
		}
	}

	public synchronized void add(Store obj)
	{
		queue.offer(obj);
		if (!this.isAlive())
		{
			this.start();
		}
		this.notify();
	}
}
